﻿using Kz.Telegram.Bot.Infrastructure.Extensions;
using Kz.Telegram.Bot.Infrastructure.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;

namespace Kz.Telegram.Bot.Infrastructure.Attributes
{
    /// <summary>
    /// Dto模型验证特性
    /// </summary>
    public class ValidateModelAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 验证动作
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var valiArr = context.ModelState.Keys
                    .SelectMany(key => context.ModelState[key]?.Errors?.Select(x => $"{key} : " + x.ErrorMessage))
                    .ToList();

                context.Result = new ObjectResult(new ApiResponse(HttpStatusCode.BadRequest, valiArr.ToJson()));
            }
        }
    }
}